﻿using CCWin.SkinControl;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;


namespace WebSocketChat.Common.Database
{
    public class Helper
    {
        public Helper()
        {

        }
        public Helper(WebSocketChatEntities context)
        {
            _context = context;
        }

        private WebSocketChatEntities _context;

        public WebSocketChatEntities Context
        {
            get
            {
                if (_context == null)
                    _context = new WebSocketChatEntities();
                return _context;
            }
        }

        public List<ChatGroup> GetChatGroups(int uid)
        {
            List<ChatGroup> groups = new List<ChatGroup>();

            var fgs = Context.FriendGroups.Where(t => t.UserID == uid).ToList();
            foreach (var item in fgs)
            {
                ChatGroup group = new ChatGroup();
                group.Group = item;
                group.Users = new List<ChatFriend>();

                var friends = Context.Friends.Where(t => t.UserID == uid && t.FriendGroupsID == item.ID).ToList();
                foreach (var friend in friends)
                {
                    group.Users.Add(new ChatFriend()
                    {
                        NickName = friend.Name,
                        User = Context.ChatUser.FirstOrDefault(t => t.ID == friend.FirendID)
                    });
                }
                groups.Add(group);
            }
            return groups;
        }

        public void ChangeUserState(int id, ChatListSubItem.UserStatus status)
        {
            var user = Context.ChatUser.FirstOrDefault(t => t.ID == id);
            if (user != null)
            {
                user.UserStateID = (int)status;
            }
            Context.SaveChanges();
        }

        public List<int> GetFriendIds(int uid)
        {
            return Context.Friends.Where(t => t.UserID == uid).Select(t => t.FirendID).ToList();
        }

        public ChatUser GetUser(int uid)
        {
            return Context.ChatUser.FirstOrDefault(t => t.ID == uid);
        }
    }
}
